<?php
namespace models\service;
//use PEAR;

class BerkasService {

	protected $ci;
	public $lastBerkas;
	
	public function __construct() {
		$this -> ci = &get_instance();
	}

	public function paginateBerkas($indexAndCount, $orders) {
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> paginateBerkas($indexAndCount, $orders);
	}

	public function paginateBerkasByMap($map, $indexAndCount, $orders) {
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> paginateBerkasByMap($map, $indexAndCount, $orders);
	}
	
	// Start Service for Jenis Data
	public function findAllPerpustakaan($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\Perpustakaan') -> findAll($orderBy);
	}
	// End Service for Jenis Data
	
	// Start Service for Indicator
	public function findAllIndicator($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\Indicator') -> findAll($orderBy);
	}
	// End Service for Indicator
	
	// Start Service for TipeBerkas
	public function findAllTipeBerkas($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\TipeBerkas') -> findAll($orderBy);
	}
	
	// Start Service for Quarter
	public function findAllQuarter($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\Quarter') -> findAll($orderBy);
	}
	// End Service for Quarter
	
	// Start Service for Distrik
	public function findAllDistrik($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\Distrik') -> findAll($orderBy);
	}
	
	public function findAllDesa($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\Desa') -> findAll($orderBy);
	}
	// End Service for Distrik
	
	// Start Service for Sector
	public function findAllSector($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\Sector') -> findAll($orderBy);
	}
	// End Service for Sector
	
	// Start Service for Package
	public function findAllPackage($orderBy=null){
		return $this -> ci -> em -> getRepository('\models\entities\Package') -> findAll($orderBy);
	}
	// End Service for Package
	
	public function paginateBarangItemByMap($map, $indexAndCount, $orders) {
		return $this -> ci -> em -> getRepository('\models\entities\BarangItem') -> paginateByMap($map, $indexAndCount, $orders);
	}
		
	public function getBerkasById($isLazzy = FALSE,$id){
		$criteria = array('id' => $id);
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> findByOne(TRUE, $criteria); 
	}
	
	/**
	 * 
	 */
	public function save($param){
			if ($param['Berkas']['id'] != "0") {
				$criteria = array('id' => $param['Berkas']['id']);
				$berkas = $this -> ci -> em -> getRepository('\models\entities\Berkas') -> findOneBy($criteria);
				//$berkas->setEventDate($now);
			} else {
				$berkas = new \models\entities\Berkas;
				$noUrut = $this->generateNewBerkasCode($param['Berkas']['tipe']);
				$berkas->setId($noUrut);
			}
			
			if (key_exists('description', $param['Berkas']) && $param['Berkas']['description'] != ""){
				$berkas->setDescription($param['Berkas']['description']);	
			}
			
			/*
			if (key_exists('eventDate', $param['Berkas']) && $param['Berkas']['eventDate'] != ""){
				$reportDate = new \DateTime($param['Berkas']['eventDate'], new \DateTimeZone("Asia/Jakarta"));
				$berkas->setEventDate($reportDate);	
			}		*/	
			
			if (key_exists('perpustakaan', $param['Berkas']) && $param['Berkas']['perpustakaan'] != ""){
				$criteria = array('id' => $param['Berkas']['perpustakaan']);
				$perpustakaan = $this->ci->em->getRepository('\models\entities\Perpustakaan')->findOneBy($criteria);
				$berkas->setPerpustakaan($perpustakaan);
			}

			if (key_exists('tipe', $param['Berkas']) && $param['Berkas']['tipe'] != ""){
				$criteria = array('id' => $param['Berkas']['tipe']);
				$tipe = $this->ci->em->getRepository('\models\entities\TipeBerkas')->findOneBy($criteria);
				$berkas->setTipe($tipe);
			}
			
			if (key_exists('reporter', $param['Berkas']) && $param['Berkas']['reporter'] != ""){
				$berkas->setReporter($param['Berkas']['reporter']);
			}

			try {			    
			    $this->ci->em->persist($berkas);
			    $this->ci->em->flush();
				//print_r($berkas);die();				
				return $berkas;
			} catch (\Exception $e) {
							    
				return FALSE;
			}
	} 
	
	public function generateNewBerkasCode($tipeBerkasId){
		$criteria = array('id' => $tipeBerkasId);
		$tipeBerkas = $this->ci->em->getRepository('\models\entities\TipeBerkas')->findOneBy($criteria);
		$prefiks = $tipeBerkas->getPrefiksCode();
		$bulan = date('m');
		$code = $prefiks.$bulan;
		//die($code);
		//echo $code;
		$noUrut = $this->ci->em->getRepository('\models\entities\Berkas')->findNoUrut($code);
		if ($noUrut == NULL){
			$code .= "0001"; 
		} else {
			$noUrut = $noUrut + 1;
			$code .= sprintf('%04d', $noUrut);
		}
		//die($code);
		return $code; 
	}
	
	public function saveBerkasAsDraft($param) {		
		if ($param != null) {			
			//echo "<pre>"; print_r($berkas);die();
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
				$berkas = $this->save($param);	
				if ($berkas === FALSE){
			    	throw new \Exception("GAGAL SAVE BERKAS");
			    }				
				if ($param['Berkas']['id'] == '0'){
					if ($this->saveBerkasIndicator($berkas, $param) === FALSE){
						throw new \Exception("GAGAL INSERT BERKASINDICATOR");
					}
					
					if ($berkas->getTipe()->getId() == "TRAINING"){
						if ($this->insertParticipantOfTraining($berkas, $param) === FALSE){
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");	
						}						
					}
					
					$inboxService = new InboxService;
					$criteria = array('id' => $param['Profile']['id']);
					$profile = $this->ci->em->getRepository('\models\entities\Profile')->findOneBy($criteria);
					if ($inboxService->startNewFlow($berkas, $profile) === FALSE){
						throw new \Exception("GAGAL START NEW FLOW");
					}
				} else {
					if ($this->saveBerkasIndicator($berkas, $param) === FALSE){
						throw new \Exception("GAGAL SAVE BERKASINDICATOR");
					}
					
					if ($berkas->getTipe()->getId() == "TRAINING"){
						$criteria = array('berkas' => $berkas);
						$members = $this -> ci -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findBy($criteria);
						if (count($members) > 0) {
							foreach ($members as $member) {
								$this -> deleteMemberOfTraining($member->getId());
							}
						}
						if ($this->insertParticipantOfTraining($berkas, $param) === FALSE){
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");	
						}						
					}
				}
				
				$criteria = array('berkas' => $berkas);
				$berkasAttachments = $this->ci->em->getRepository('\models\entities\BerkasAttachment')->findBy($criteria);
				if (count($berkasAttachments) > 0){
					foreach ($berkasAttachments as $berkasAttachment){
						$this->deleteBerkasAttachment($berkasAttachment->getId());
					}
				}
				if ($this->insertBerkasAttachment($berkas, $_FILES) ===FALSE){
					throw new \Exception("GAGAL UPLOAD DOC");
				}
				
				$this->ci->em->getConnection()->commit();
				$this -> lastBerkas = $berkas;				
				
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo $e->getMessage();
			    //var_dump($e);
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function insertBerkasAttachment($berkas, $files){
		// die($berkas->getId());
		$path = './attach/'. $berkas->getId()."/";
		
		if (!is_dir($path)) {
		    mkdir($path, 0777, TRUE);		
		}
		//echo "<pre>"; print_r($files);
		//die();
		
		if (array_key_exists('attach1',$_FILES) || array_key_exists('attach2',$_FILES) || array_key_exists('attach3',$_FILES) || array_key_exists('attach4',$_FILES)
			|| array_key_exists('attach5',$_FILES)){
			$i = 0;
			$config['upload_path'] = $path;
			$config['allowed_types'] = 'pdf|jpg|jpeg|png|doc|docx|xls|xlsx';
			$config['overwrite'] = true;
			foreach ($files as $key => $value){
				$this -> ci -> load -> library('upload', $config);
				//$this->upload->initialize($config);
				if (!empty($value)  && $files[$key]['error'] == 0){
					if (!$this -> ci -> upload -> do_upload($key)) {
						$error = array('error' => $this -> ci -> upload -> display_errors());
						// FIX TO : send error notification
						echo "<pre> $key => $value";
						print_r($files);
						print_r($error);
						die('ERROR UPLOAD');
						return FALSE;
					} else {
						$data = array('upload_data' => $this -> ci -> upload -> data());
						$berkasAttachment = new \models\entities\BerkasAttachment;
						$berkasAttachment->setBerkas($berkas);
						$berkasAttachment->setStatus(1);
						$berkasAttachment->setPath($path.$data['upload_data']['file_name']);					 
						$berkasAttachment->setTypeFile($files[$key]['type']);
						try {
							$this->ci->em->persist($berkasAttachment);
						    $this->ci->em->flush();	
							
						} catch (Exception $e){
							die("ERR EXCepTION : ".$e->getMessage());
							return FALSE;
						}
					}	
				}				
			}
			return TRUE;
				
		} 		
	}

	public function saveBerkasIndicator($berkas, $param){
		if ($berkas != NULL){
			//echo $berkas->getId();
			if ($berkas->getTipe()->getId() == "TRAINING"){
				if ($param['Berkas']['id'] != '0'){
					$criteria = array('id' => $berkas);
					$berkasIndicator = $this->ci->em->getRepository('\models\entities\BerkasTraining')->findOneBy($criteria);
				} else {
					$berkasIndicator = new \models\entities\BerkasTraining;
					$berkasIndicator->setId($berkas);	
				}
				//$berkasIndicator = new \models\entities\BerkasTraining;		
				$criteria = array('id' => $param['BerkasTraining']['jenisTraining']);
				$jenisTraining = $this->ci->em->getRepository('\models\entities\JenisTraining')->findOneBy($criteria);				
				$berkasIndicator->setJenisTraining($jenisTraining);
				$berkasIndicator->setJmlStaff($param['BerkasTraining']['jmlStaff']);
				$berkasIndicator->setJmlNonStaff($param['BerkasTraining']['jmlNonStaff']);			
				$berkasIndicator->setJmlPria($param['BerkasTraining']['jmlPria']);
				$berkasIndicator->setJmlWanita($param['BerkasTraining']['jmlWanita']);
				if (key_exists('fromDate', $param['BerkasTraining']) && $param['BerkasTraining']['fromDate'] != ""){
					$fromDate = new \DateTime($param['BerkasTraining']['fromDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator->setFromDate($fromDate);	
				}
				
				if (key_exists('toDate', $param['BerkasTraining']) && $param['BerkasTraining']['toDate'] != ""){
					$toDate = new \DateTime($param['BerkasTraining']['toDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator->setToDate($toDate);	
				}
			} else {
				return TRUE;
			}
			
			try {
				$this->ci->em->persist($berkasIndicator);
			    $this->ci->em->flush();	
				return TRUE;
			} catch (Exception $e){
				return FALSE;
			}				
			
		} else {
			return FALSE;
		}		
	}
	
	public function insertParticipantOfTraining($berkas, $param){
		if ($berkas != NULL){
			if ($berkas->getTipe()->getId() == "TRAINING" && is_array($param['0'])){
				foreach ($param['0']['MemberOfTraining'] as $row){
					$participant = new \models\entities\ParticipantOfTraining;
					$participant->setName($row['name']);
					$participant->setGender($row['gender']);
					$participant->setStaff($row['staff']);
					$participant->setBerkas($berkas);
					try {
						$this->ci->em->persist($participant);
					    $this->ci->em->flush();	
						//return TRUE;
					} catch (Exception $e){
						return FALSE;
					} 	
				}		
				return TRUE;
			} else {
				return TRUE;
			}					
			
		} else {
			return FALSE;
		}		
	}

	public function saveAndSubmitBerkas($param){
		if ($param != NULL){
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
				$berkas = $this->save($param);			    
			    if ($berkas === FALSE){
			    	throw new \Exception("GAGAL SAVE BERKAS");
			    }				
				if ($param['Berkas']['id'] == '0'){
					if ($this->saveBerkasIndicator($berkas, $param) === FALSE){
						throw new \Exception("GAGAL INSERT BERKASINDICATOR");
					}
					
					if ($berkas->getTipe()->getId() == "TRAINING"){
						if ($this->insertParticipantOfTraining($berkas, $param) === FALSE){
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");	
						}						
					}
					
					$inboxService = new InboxService;
					$criteria = array('id' => $param['Profile']['id']);
					$profile = $this->ci->em->getRepository('\models\entities\Profile')->findOneBy($criteria);
					if ($inboxService->startNewFlow($berkas, $profile) === FALSE){
						throw new \Exception("GAGAL START NEW FLOW");
					}
				} else {
					if ($this->saveBerkasIndicator($berkas, $param) === FALSE){
						throw new \Exception("GAGAL SAVE BERKASINDICATOR");
					}
					
					if ($berkas->getTipe()->getId() == "TRAINING"){
						$criteria = array('berkas' => $berkas);
						$members = $this -> ci -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findBy($criteria);
						if (count($members) > 0) {
							foreach ($members as $member) {
								$this -> deleteMemberOfTraining($member->getId());
							}
						}
						if ($this->insertParticipantOfTraining($berkas, $param) === FALSE){
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");	
						}						
					}
				}				
				
				$criteria = array('id' => $param['Profile']['id']);
				$profile = $this->ci->em->getRepository('\models\entities\Profile')->findOneBy($criteria);
				
				$criteria = array('id' => $berkas);
				$inbox = $this->ci->em->getRepository('\models\entities\Inbox')->findOneBy($criteria);
				
				$inboxService = new InboxService;
				if ($inboxService->nextInboxStep($inbox, $profile, 'OK') === FALSE){
					throw new \Exception("GAGAL NEXT INBOX STEP");
				}
				
				// insert new berkasComment
				$berkasText = $this->ci->input->post('BerkasComment_text');
				if ($berkasText != ''){
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment->setBerkas($berkas);
					$procedureStepId = $this->ci->input->post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this->ci->em->getRepository('\models\entities\ProcedureStep')->findOneBy($criteria);
					$berkasComment->setProcedureStep($ps);
					$user = \models\service\CurrentUser::user();
					$berkasComment->setSender($user->getUserId());
					$berkasComment->setText($berkasText);
					$this->ci->em->persist($berkasComment);
					$this->ci->em->flush();
				}
				
				$criteria = array('berkas' => $berkas);
				$berkasAttachments = $this->ci->em->getRepository('\models\entities\BerkasAttachment')->findBy($criteria);
				if (count($berkasAttachments) > 0){
					foreach ($berkasAttachments as $berkasAttachment){
						$this->deleteBerkasAttachment($berkasAttachment->getId());
					}
				}
				if ($this->insertBerkasAttachment($berkas, $_FILES) ===FALSE){
					throw new \Exception("GAGAL UPLOAD DOC");
				}
				$this->ci->em->getConnection()->commit();
				$this -> lastBerkas = $berkas;				
				
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo $e->getMessage();
			    
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function submitBerkas($berkas, $profileId){
		if ($berkas != NULL){
			$user = \models\service\CurrentUser::user();
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
				$criteria = array('id' => $profileId);
				$profile = $this->ci->em->getRepository('\models\entities\Profile')->findOneBy($criteria);
				
				$criteria = array('id' => $berkas->getId());
				$inbox = $this->ci->em->getRepository('\models\entities\Inbox')->findOneBy($criteria);
				
				$inboxService = new InboxService;
				$cond = 'OK';
				if ($inbox->getProcedureStep()->getId()==3){
					$cond = 'FINISH';
					$berkas->setApprover($user->getUserId());
					$berkas->setEndDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));				
				} else if ($inbox->getProcedureStep()->getId()==2){
					$berkas->setVerifier($user->getUserId());
				}
				$berkas->setResult($cond);
				
				$this->ci->em->persist($berkas);
				$this->ci->em->flush();
				
				if ($inboxService->nextInboxStep($inbox, $profile, $cond) === FALSE){
					throw new \Exception("GAGAL NEXT INBOX STEP");
				}
				
				// update berkas
				 
				// insert new berkasComment
				$berkasText = $this->ci->input->post('BerkasComment_text');
				if ($berkasText != ''){
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment->setBerkas($berkas);
					$procedureStepId = $this->ci->input->post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this->ci->em->getRepository('\models\entities\ProcedureStep')->findOneBy($criteria);
					$berkasComment->setProcedureStep($ps);
					$user = \models\service\CurrentUser::user();
					$berkasComment->setSender($user->getUserId());
					$berkasComment->setText($berkasText);
					$this->ci->em->persist($berkasComment);
					$this->ci->em->flush();
				} 
					
				$this->ci->em->getConnection()->commit();
				$this -> lastBerkas = $berkas;				
				
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo $e->getMessage();
			    
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function submitBerkasForVerAndApp($berkas, $profileId, $cond = "OK"){
		if ($berkas != NULL){
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
				if ($cond == "OK" || $cond == "NOK" || $cond == "FINISH"){
					$this->ci->em->persist($berkas);
					$this->ci->em->flush();	
					
					// insert new berkasComment
					$berkasText = $this->ci->input->post('BerkasComment_text');
					if ($berkasText != ''){
						$berkasComment = new \models\entities\BerkasComment;
						$berkasComment->setBerkas($berkas);
						$procedureStepId = $this->ci->input->post('ProcedureStep_id');
						$criteria = array('id' => $procedureStepId);
						$ps = $this->ci->em->getRepository('\models\entities\ProcedureStep')->findOneBy($criteria);
						$berkasComment->setProcedureStep($ps);
						$user = \models\service\CurrentUser::user();
						$berkasComment->setSender($user->getUserId());
						$berkasComment->setText($berkasText);
						$this->ci->em->persist($berkasComment);
						$this->ci->em->flush();
					} 
				}	
				
				if ($cond == "CANCEL"){
					$berkas->setResult("CANCEL");
					$this->ci->em->persist($berkas);
					$this->ci->em->flush();
				}			
				
				$criteria = array('id' => $profileId);
				$profile = $this->ci->em->getRepository('\models\entities\Profile')->findOneBy($criteria);
				
				$criteria = array('id' => $berkas->getId());
				$inbox = $this->ci->em->getRepository('\models\entities\Inbox')->findOneBy($criteria);
				
				$inboxService = new InboxService;
				if ($inboxService->nextInboxStep($inbox, $profile, $cond) === FALSE){
					throw new \Exception("GAGAL NEXT INBOX STEP");
				}
				$this->ci->em->getConnection()->commit();
				$this -> lastBerkas = $berkas;				
				
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo $e->getMessage();
			    
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function deleteMemberOfTraining($id) {
		if ($id > 0) {
			$criteria = array('id' => $id);
			$item = $this -> ci -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findOneBy($criteria);
			$this -> ci -> em -> remove($item);
			$this -> ci -> em -> flush();

			return TRUE;
		}

		return FALSE;
	}

	public function deleteBerkasAttachment($id) {
		if ($id > 0) {
			$criteria = array('id' => $id);
			$item = $this -> ci -> em -> getRepository('\models\entities\BerkasAttachment') -> findOneBy($criteria);
			$this -> ci -> em -> remove($item);
			$this -> ci -> em -> flush();

			return TRUE;
		}

		return FALSE;
	}
	
	public function submitReview($berkas, $profileId, $cond = "OK"){
		if ($berkas != NULL){
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
				$this->ci->em->persist($berkas);
				$this->ci->em->flush();
				$user = \models\service\CurrentUser::user();
				// insert new berkasComment
				$berkasText = $this->ci->input->post('BerkasComment_text');
				if ($berkasText != ''){
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment->setBerkas($berkas);
					$procedureStepId = $this->ci->input->post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this->ci->em->getRepository('\models\entities\ProcedureStep')->findOneBy($criteria);
					$berkasComment->setProcedureStep($ps);
					
					$berkasComment->setSender($user->getUserId());
					$berkasComment->setText($berkasText);
					$this->ci->em->persist($berkasComment);
					$this->ci->em->flush();
				} 
				
				$criteria = array('id' => $profileId);
				$profile = $this->ci->em->getRepository('\models\entities\Profile')->findOneBy($criteria);
				
				$criteria = array('id' => $berkas->getId());
				$inbox = $this->ci->em->getRepository('\models\entities\Inbox')->findOneBy($criteria);
				
				/*$criteria = array('userId' => $user);
				$userVerifikator = $this->ci->em->getRepository('\models\entities\UserVerifikator')->findBy($criteria);
				if ($userVerifikator[0]->getJenisVerifikator()->getId()==2){
					$inbox->setJumlahVerify(1);
					$inbox->setLastVer($user->getUserId());
					$this->ci->em->persist($inbox);
					$this->ci->em->flush();	
				}*/
				if ($inbox->getProcedureStep()->getVerifyByJumlah() != NULL && $inbox->getProcedureStep()->getVerifyByJumlah() > 0){
					$jmlh = $inbox->getJumlahVerify();
					if ($jmlh == NULL){
						$jmlh = 0;
					}
					$inbox->setJumlahVerify($jmlh + 1);
					$inbox->setLastVer($user->getUserId());
					$this->ci->em->persist($inbox);
					$this->ci->em->flush();
				}				
				
				$berkasActivity = new \models\entities\BerkasActivity;
				$berkasActivity->setBerkas($berkas);
				$berkasActivity->setProcedureStep($inbox->getProcedureStep());
				$berkasActivity->setProfile($profile);
				if ($profileId == 9){
					$berkasActivity->setAction("APPROVED");
				} else {
					$berkasActivity->setAction("REVIEW");	
				}
				
				$user = CurrentUser::user();
				$berkasActivity->setUser($user->getUserId());
					
				$this->ci->em->persist($berkasActivity);
				$this->ci->em->flush();
				
				$this->ci->em->getConnection()->commit();
				$this -> lastBerkas = $berkas;				
				
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo $e->getMessage();
			    
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function submitFirstApprove($berkas, $profileId, $cond = "OK"){
		if ($berkas != NULL){
			$this->ci->em->getConnection()->beginTransaction(); // suspend auto-commit
			try {
				$this->ci->em->persist($berkas);
				$this->ci->em->flush();
				$user = \models\service\CurrentUser::user();
				// insert new berkasComment
				$berkasText = $this->ci->input->post('BerkasComment_text');
				if ($berkasText != ''){
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment->setBerkas($berkas);
					$procedureStepId = $this->ci->input->post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this->ci->em->getRepository('\models\entities\ProcedureStep')->findOneBy($criteria);
					$berkasComment->setProcedureStep($ps);
					
					$berkasComment->setSender($user->getUserId());
					$berkasComment->setText($berkasText);
					$this->ci->em->persist($berkasComment);
					$this->ci->em->flush();
				} 
				
				$criteria = array('id' => $profileId);
				$profile = $this->ci->em->getRepository('\models\entities\Profile')->findOneBy($criteria);
				
				$criteria = array('id' => $berkas);
				$inbox = $this->ci->em->getRepository('\models\entities\Inbox')->findOneBy($criteria);
				
				$criteria = array('userId' => $user);
				$userVerifikator = $this->ci->em->getRepository('\models\entities\UserVerifikator')->findBy($criteria);
				
				if ($inbox->getJumlahApprover() == null || $inbox->getJumlahApprover() < 1){
					$inbox->setJumlahApprover(1);
					$inbox->setLastApp($user->getUserId());
					$this->ci->em->persist($inbox);
					$this->ci->em->flush();	
				}				
				
				$berkasActivity = new \models\entities\BerkasActivity;
				$berkasActivity->setBerkas($berkas);
				$berkasActivity->setProcedureStep($inbox->getProcedureStep());
				$berkasActivity->setProfile($profile);
				$berkasActivity->setAction("FIRST APPROVE");
				$user = CurrentUser::user();
				$berkasActivity->setUser($user->getUserId());
					
				$this->ci->em->persist($berkasActivity);
				$this->ci->em->flush();
				
				$this->ci->em->getConnection()->commit();
				$this -> lastBerkas = $berkas;				
				
			} catch (\Exception $e) {
			    $this->ci->em->getConnection()->rollback();
			    $this->ci->em->close();
				echo $e->getMessage();
			    
				return FALSE;
			}			
			
			return TRUE;
		} else {
			return FALSE;
		}
	}	
}
